from celery import shared_task
from .models import City, Datacenter, Host, HostCount
from datetime import date
import string
import random


# 生成随机密码
def generate_random_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password


def update_pwd(host, city_name, datacenter_name, new_password):
    """
    需要根据不同系统修改密码

    """


# 每8小时执行的任务
@shared_task
def every_eight_hours_task():
    host_list = Host.objects.all()
    for host in host_list:
        # 根据实际情况修改主机密码
        hostname = host.hostname
        city_name = host.city_name
        datacenter_name = host.datacenter_name
        new_password = generate_random_password()
        update_pwd_res = update_pwd(hostname, city_name, datacenter_name, new_password)
        host.root_password = new_password
        host.save()

    return True


# 每天执行的任务
@shared_task
def daily_midnight_task():
    # 获取当前日期
    current_date = date.today()
    city_list = City.objects.all()
    for city in city_list:
        city_name = city.name
        datacenter_list = Datacenter.objects.filter(city_name=city_name)
        for datacenter in datacenter_list:
            datacenter_host = {}
            datacenter_name = datacenter.name
            datacenter_host['city_name'] = city_name
            datacenter_host['datacenter_name'] = datacenter_name
            host_list = Host.objects.filter(city_name=city_name, datacenter_name=datacenter_name)
            count = host_list.count()
            datacenter_host['host_count'] = count
            datacenter_host['publication_date'] = current_date
            insert_hostcount = HostCount.objects.create(**datacenter_host)

    return True
